package com.lingrit.provider.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import com.lingrit.provider.config.SysProperties;
import com.lingrit.provider.exception.ExceptionMsg;
import com.lingrit.provider.exception.FpException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

/**
 * @author qlkj
 */
@Component
public class TokenUtils {

    @Autowired
    private SysProperties sysProperties;
    

    public  String createToken(String id){
        try {
            Algorithm algorithm = Algorithm.HMAC256(sysProperties.getSecret());
//            Map<String, Object> map = new HashMap<>();
//            map.put("name",name);
//            map.put("password",password);
            Date expiredDate = new Date(System.currentTimeMillis() + sysProperties.getExpiration());
            String token = JWT.create()
                    .withClaim("id",id)
//                    .withClaim("name",name)
//                    .withClaim("password",password)
//                    .withHeader(map)
                    .withExpiresAt(expiredDate)
                    .sign(algorithm);
            return token;
        } catch (Exception exception){
            throw new FpException(exception,ExceptionMsg.TOKEN_CREATE);
        }
    }

    private Date addExpiredDate(Date expiredDate) {

        return null;
    }

    public   String parseToken(String token){
        try {
            Algorithm algorithm = Algorithm.HMAC256(sysProperties.getSecret());
            JWTVerifier verifier = JWT.require(algorithm)
                    .build();
            DecodedJWT jwt = verifier.verify(token);
            jwt.getExpiresAt();

            Map<String, Claim> claims = jwt.getClaims();
            String id = claims.get("id").asString();
            return id;
        } catch (Exception exception){
            throw new FpException( ExceptionMsg.TOKEN_VERIFY.getMessage(),exception);
        }



    }

}
